package org.jaaksi.test.handler;

import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.widget.Button;

/**
 * Created by Fcy on 2015/9/21.<br/>
 * 利用handler实现常见的注册发送短信消息的倒计时
 */
public class CountdownActivity extends Activity implements View.OnClickListener {

    private Button btn;

    private final int TIME_LIMIT = 10;
    private final int MSG = 0;

    private int time = TIME_LIMIT;

    private Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            if (msg.what == MSG) {
                if (time > 0) {
                    if (time == 5) {
                        tip.setVisibility(View.VISIBLE);
                    }
                    btn.setText("(" + time + ")" + "秒后重发");
                    time--;
                    mHandler.sendEmptyMessageDelayed(MSG, 1000);
                } else {
                    // 重置时间
                    time = TIME_LIMIT;
                    btn.setText("发送验证码");
                    btn.setEnabled(true);
                    mHandler.removeMessages(MSG);
                }
            }
        }
    };
    private View tip;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.countdown);

        btn = (Button) findViewById(R.id.btn);
        btn.setOnClickListener(this);

        tip = findViewById(R.id.tip);
    }

    @Override
    public void onClick(View v) {
        if (v.getId() == R.id.btn) {
            // TODO 点击后转圈提醒，进行网络请求，成功后执行下面代码
            mHandler.sendEmptyMessage(MSG);
            btn.setEnabled(false);
        }
    }
}